package com.xgame.controller.pb;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import com.common.JunitCommon;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.spring.http.ProtobufHttpMessageConverter;
import com.xgame.poto.BasePacket.Packet;
import com.xgame.poto.UserProto.UserPb;

/**
 * @author zhaowei
 */
public class BastTestMethod extends JunitCommon {
	protected final RestTemplate restTemplate = new RestTemplate();
	{
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
		messageConverters.add(new ProtobufHttpMessageConverter());
		restTemplate.setMessageConverters(messageConverters);
		HttpHeaders headers = new HttpHeaders();
		MediaType mediaType = new MediaType("x", "pb");
		headers.setContentType(mediaType);
		headers.setContentType(mediaType);
	}

	public void test() {
		String url = "http://localhost:8080/x/login";
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
		messageConverters.add(new ProtobufHttpMessageConverter());
		restTemplate.setMessageConverters(messageConverters);
		HttpHeaders headers = new HttpHeaders();
		UserPb userPb = UserPb.newBuilder().setUserName("赵巍")
				.setPassword("123456").build();
		MediaType mediaType = new MediaType("x", "pb");
		headers.setContentType(mediaType);
		HttpEntity<UserPb> request = new HttpEntity<UserPb>(userPb, headers);
		Long begin = System.currentTimeMillis();
		Packet pack = restTemplate.postForObject(url, request, Packet.class);
		System.out.println(pack.getData().toString());
		UserPb userPb2;
		try {
			userPb2 = UserPb.parseFrom(pack.getData());
			System.out.println("服务端返回" + userPb2.getUserName());
			Long end = System.currentTimeMillis();
			System.out.println("请求处理时间：" + (end - begin));
			System.out.println("header大小：" + request.getHeaders().size());
			System.out.println("request序列化后的大小："
					+ request.getBody().getSerializedSize());
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
		}
	}

	// public static void main(String[] args) throws IOException {
	//
	// new UserControllerTest().test();
	// // String url = "http://localhost:8080/s/pbtest/upload.pb";
	// // upload(url);
	// // String url2 = "http://www.example.com/pbtest/download.pb";
	// // download(url2);
	// }
}
